package com.xy.blog.user.controller;

import com.xy.blog.core.exception.BaseException;
import com.xy.blog.core.springmvc.controller.BaseController;
import com.xy.blog.core.springmvc.controller.IBaseController;
import com.xy.blog.core.springmvc.result.page.PageReq;
import com.xy.blog.user.controller.model.req.AccountReq;
import com.xy.blog.user.controller.model.req.LoginReq;
import com.xy.blog.user.controller.model.req.query.AccountQuery;
import com.xy.blog.user.mapstruct.AccountConverter;
import com.xy.blog.user.service.impl.AccountServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description: 账号管理
 * @date 2020/3/7
 */
@Api(value = "AccountController", tags = "账号管理")
@RequestMapping("/v1/account")
@RestController
public class AccountController extends BaseController implements IBaseController<AccountQuery, AccountReq> {

    @Autowired
    private AccountServiceImpl accountServiceImpl;

    @Autowired
    private AccountConverter accountConverter;

    /**
     * @param req
     * @return
     * @throws BaseException
     */
    @Override
    public Object pages(PageReq<AccountQuery> req) throws BaseException {
        return getPageData(accountServiceImpl.listByPage(req));
    }

    @Override
    public Object getById(Long id) throws BaseException {
        return getData(accountServiceImpl.getById(id));
    }

    /**
     * 开通账号
     *
     * @param req
     * @return
     * @throws BaseException
     */
    @Override
    public Object save(@Valid AccountReq req) throws BaseException {
        accountServiceImpl.save(accountConverter.req2Bo(req));
        return success();
    }

    @Override
    public Object update(@Valid AccountReq req) throws BaseException {
        accountServiceImpl.update(accountConverter.req2Bo(req));
        return success();
    }

    @Override
    public Object deleteById(Long id) throws BaseException {
        accountServiceImpl.deleteById(id);
        return success();
    }

    /**
     * 登录
     *
     * @param req
     * @return
     */
    @PostMapping("/login")
    public Object login(@Valid @RequestBody LoginReq req) {
        return getData(accountServiceImpl.login(req.getAccount(), req.getPassword()));
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public Object logout(HttpServletRequest request) {
        accountServiceImpl.logout(request.getHeader("token"));
        return success();
    }

    @GetMapping("/validate-token")
    public Object validateToken(@RequestParam("token") String token) {
        return getData(accountServiceImpl.validateToken(token));
    }


}
